{% extends 'base.html' %}
{% load static %}

{% block title %}仪表板 - CFS Web System{% endblock %}

{% block page_type %}dashboard{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item active">仪表板</li>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 页面标题 -->
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-tachometer-alt me-2"></i>系统仪表板</h2>
            <div class="btn-group">
                <button type="button" class="btn btn-outline-primary" onclick="location.reload()">
                    <i class="fas fa-sync-alt"></i> 刷新
                </button>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#quickActionModal">
                    <i class="fas fa-plus"></i> 快速操作
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card stat-card-primary">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col">
                        <h5 class="card-title text-uppercase text-muted mb-0">总模板数</h5>
                        <span class="h2 font-weight-bold mb-0" id="total-templates">{{ stats.total_templates|default:0 }}</span>
                    </div>
                    <div class="col-auto">
                        <div class="icon icon-shape bg-primary text-white rounded-circle shadow">
                            <i class="fas fa-file-alt"></i>
                        </div>
                    </div>
                </div>
                <p class="mt-3 mb-0 text-muted text-sm">
                    <span class="text-success mr-2">
                        <i class="fas fa-arrow-up"></i> {{ stats.templates_growth|default:0 }}%
                    </span>
                    <span class="text-nowrap">较上月</span>
                </p>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card stat-card-success">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col">
                        <h5 class="card-title text-uppercase text-muted mb-0">上传文件数</h5>
                        <span class="h2 font-weight-bold mb-0" id="total-files">{{ stats.total_files|default:0 }}</span>
                    </div>
                    <div class="col-auto">
                        <div class="icon icon-shape bg-success text-white rounded-circle shadow">
                            <i class="fas fa-file-upload"></i>
                        </div>
                    </div>
                </div>
                <p class="mt-3 mb-0 text-muted text-sm">
                    <span class="text-success mr-2">
                        <i class="fas fa-arrow-up"></i> {{ stats.files_growth|default:0 }}%
                    </span>
                    <span class="text-nowrap">较上月</span>
                </p>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card stat-card-warning">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col">
                        <h5 class="card-title text-uppercase text-muted mb-0">处理任务数</h5>
                        <span class="h2 font-weight-bold mb-0" id="total-tasks">{{ stats.total_tasks|default:0 }}</span>
                    </div>
                    <div class="col-auto">
                        <div class="icon icon-shape bg-warning text-white rounded-circle shadow">
                            <i class="fas fa-tasks"></i>
                        </div>
                    </div>
                </div>
                <p class="mt-3 mb-0 text-muted text-sm">
                    <span class="text-warning mr-2">
                        <i class="fas fa-clock"></i> {{ stats.pending_tasks|default:0 }}
                    </span>
                    <span class="text-nowrap">待处理</span>
                </p>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card stat-card-info">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col">
                        <h5 class="card-title text-uppercase text-muted mb-0">系统状态</h5>
                        <span class="h2 font-weight-bold mb-0 text-success">正常</span>
                    </div>
                    <div class="col-auto">
                        <div class="icon icon-shape bg-info text-white rounded-circle shadow">
                            <i class="fas fa-heartbeat"></i>
                        </div>
                    </div>
                </div>
                <p class="mt-3 mb-0 text-muted text-sm">
                    <span class="text-success mr-2">
                        <i class="fas fa-check"></i> 运行时间
                    </span>
                    <span class="text-nowrap">{{ stats.uptime|default:'未知' }}</span>
                </p>
            </div>
        </div>
    </div>
</div>

<!-- 主要内容区域 -->
<div class="row">
    <!-- 最近任务 -->
    <div class="col-lg-8 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-clock me-2"></i>最近任务
                </h5>
                <a href="{% url 'excel_processor:status' %}" class="btn btn-sm btn-outline-primary">
                    查看全部
                </a>
            </div>
            <div class="card-body">
                <div id="recent-tasks">
                    {% if recent_tasks %}
                        {% for task in recent_tasks %}
                        <div class="d-flex align-items-center mb-3 pb-3 border-bottom">
                            <div class="flex-shrink-0">
                                <div class="status-badge status-{{ task.status }}"></div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h6 class="mb-1">{{ task.name }}</h6>
                                <p class="text-muted mb-0">{{ task.template_name|default:'未指定模板' }}</p>
                            </div>
                            <div class="flex-shrink-0">
                                <small class="text-muted">{{ task.created_at|timesince }}前</small>
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="text-center py-4">
                            <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                            <p class="text-muted">暂无最近任务</p>
                            <a href="{% url 'data_processing:data_generation' %}" class="btn btn-primary">
                                <i class="fas fa-plus"></i> 创建新任务
                            </a>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
    
    <!-- 快速操作 -->
    <div class="col-lg-4 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-bolt me-2"></i>快速操作
                </h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="{% url 'data_processing:data_generation' %}" class="btn btn-primary">
                        <i class="fas fa-upload me-2"></i>上传文件
                    </a>
                    <a href="{% url 'template_management:template_create' %}" class="btn btn-success">
                        <i class="fas fa-plus me-2"></i>创建模板
                    </a>
                    <a href="{% url 'data_processing:data_generation' %}" class="btn btn-warning">
                        <i class="fas fa-magic me-2"></i>生成数据
                    </a>
                    <a href="{% url 'analytics:log_viewer' %}" class="btn btn-info">
                        <i class="fas fa-chart-line me-2"></i>查看日志
                    </a>
                </div>
            </div>
        </div>
        
        <!-- 系统信息 -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-info-circle me-2"></i>系统信息
                </h5>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="border-end">
                            <h6 class="text-muted">存储使用</h6>
                            <h4 class="mb-0">{{ stats.storage_used|default:'0 MB' }}</h4>
                        </div>
                    </div>
                    <div class="col-6">
                        <h6 class="text-muted">内存使用</h6>
                        <h4 class="mb-0">{{ stats.memory_used|default:'0%' }}</h4>
                    </div>
                </div>
                <hr>
                <div class="text-center">
                    <small class="text-muted">
                        最后更新: {{ stats.last_updated|default:'刚刚' }}
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 图表区域 -->
<div class="row">
    <div class="col-lg-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-chart-bar me-2"></i>文件类型分布
                </h5>
            </div>
            <div class="card-body">
                <canvas id="fileTypeChart" height="300"></canvas>
            </div>
        </div>
    </div>
    
    <div class="col-lg-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-chart-line me-2"></i>任务处理趋势
                </h5>
            </div>
            <div class="card-body">
                <canvas id="taskTrendChart" height="300"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- 快速操作模态框 -->
<div class="modal fade" id="quickActionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-bolt me-2"></i>快速操作
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <a href="{% url 'data_processing:data_generation' %}" class="card text-decoration-none h-100">
                            <div class="card-body text-center">
                                <i class="fas fa-upload fa-2x text-primary mb-2"></i>
                                <h6>上传文件</h6>
                                <p class="text-muted small mb-0">上传Excel或CSV文件</p>
                            </div>
                        </a>
                    </div>
                    <div class="col-md-6 mb-3">
                        <a href="{% url 'template_management:template_create' %}" class="card text-decoration-none h-100">
                            <div class="card-body text-center">
                                <i class="fas fa-plus fa-2x text-success mb-2"></i>
                                <h6>创建模板</h6>
                                <p class="text-muted small mb-0">创建新的处理模板</p>
                            </div>
                        </a>
                    </div>
                    <div class="col-md-6 mb-3">
                        <a href="{% url 'data_processing:data_generation' %}" class="card text-decoration-none h-100">
                            <div class="card-body text-center">
                                <i class="fas fa-magic fa-2x text-warning mb-2"></i>
                                <h6>生成数据</h6>
                                <p class="text-muted small mb-0">基于模板生成数据</p>
                            </div>
                        </a>
                    </div>
                    <div class="col-md-6 mb-3">
                        <a href="{% url 'analytics:log_viewer' %}" class="card text-decoration-none h-100">
                            <div class="card-body text-center">
                                <i class="fas fa-chart-line fa-2x text-info mb-2"></i>
                                <h6>查看日志</h6>
                                <p class="text-muted small mb-0">查看系统运行日志</p>
                            </div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// 文件类型分布图表
try {
    const fileTypeLabels = '{{ file_type_labels|escapejs }}' ? JSON.parse('{{ file_type_labels|escapejs }}') : ['Excel', 'CSV', 'PDF'];
    const fileTypeData = '{{ file_type_data|escapejs }}' ? JSON.parse('{{ file_type_data|escapejs }}') : [10, 5, 2];
    const fileTypeCtx = document.getElementById('fileTypeChart').getContext('2d');
    const fileTypeChart = new Chart(fileTypeCtx, {
        type: 'doughnut',
        data: {
            labels: fileTypeLabels,
            datasets: [{
                data: fileTypeData,
                backgroundColor: [
                    '#007bff',
                    '#28a745',
                    '#ffc107',
                    '#dc3545',
                    '#6c757d'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
} catch (error) {
    console.error('文件类型图表初始化失败:', error);
}

// 任务处理趋势图表
try {
    const trendLabels = '{{ trend_labels|escapejs }}' ? JSON.parse('{{ trend_labels|escapejs }}') : ['周一', '周二', '周三', '周四', '周五'];
    const completedTasks = '{{ completed_tasks|escapejs }}' ? JSON.parse('{{ completed_tasks|escapejs }}') : [12, 19, 3, 5, 2];
    const failedTasks = '{{ failed_tasks|escapejs }}' ? JSON.parse('{{ failed_tasks|escapejs }}') : [2, 3, 1, 0, 1];
    const taskTrendCtx = document.getElementById('taskTrendChart').getContext('2d');
    const taskTrendChart = new Chart(taskTrendCtx, {
        type: 'line',
        data: {
            labels: trendLabels,
            datasets: [{
                label: '已完成',
                data: completedTasks,
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                tension: 0.4
            }, {
                label: '失败',
                data: failedTasks,
                borderColor: '#dc3545',
                backgroundColor: 'rgba(220, 53, 69, 0.1)',
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            },
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
} catch (error) {
    console.error('任务趋势图表初始化失败:', error);
}

// 定时刷新数据
setInterval(function() {
    // 刷新统计数据
    fetch('/api/core/dashboard/stats/')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.stats) {
                if (data.stats.templates) {
                    document.getElementById('total-templates').textContent = data.stats.templates.total || 0;
                }
                if (data.stats.files) {
                    document.getElementById('total-files').textContent = data.stats.files.total || 0;
                }
                if (data.stats.tasks) {
                    document.getElementById('total-tasks').textContent = data.stats.tasks.total || 0;
                }
            }
        })
        .catch(error => console.error('刷新统计数据失败:', error));
}, 30000); // 30秒刷新一次
</script>
{% endblock %}